package main

import (
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"

	"gitee.com/general252/gorm_dm"
)

type Product struct {
	gorm.Model
	Code  string
	Price uint
}

func main() {
	db, err := gorm.Open(gorm_dm.Open("dm://SYSDBA:123456@192.168.6.59:5236"))
	if err != nil {
		log.Printf("failed to connect database. %v", err)
		return
	}

	db.Logger = logger.Default.LogMode(logger.Info)

	// 迁移 schema
	_ = db.AutoMigrate(&Product{})
	// Create
	db.Create(&Product{Code: "D42", Price: 100})

	// Read
	var product Product
	//此处加上会带上id和下一句拼接，查询语句为取一条delete_at为空的id，并把id作为条件加到后面语句
	//db.First(&product) // 根据整型主键查找
	db.First(&product, "\"code\" = ?", "D42") // 查找 code 字段值为 D42 的记录
	log.Printf(">>>>>>>>>>>>> %+v", product)

	// Update - 将 product 的 price 更新为 200
	db.Model(&product).Update("price", 200)
	// Update - 更新多个字段
	db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // 仅更新非零值字段
	db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})

	db.First(&product)
	log.Printf(">>>>>>>>>>>>> %+v", product)

	// Delete - 删除 product
	db.Delete(&product, 1)
}
